package com.shop.cereshop.app.dl.logic.demo;

import java.io.*;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;


/**
 * 获取微信apiclient_cert.p12证书
 */
@Component
public class CertHttpUtil {

    private static int socketTimeout = 10000;// 连接超时时间，默认10秒
    private static int connectTimeout = 30000;// 传输超时时间，默认30秒
    private static RequestConfig requestConfig;// 请求器的配置
    private static CloseableHttpClient httpClient;// HTTP请求器

    /**
     * 通过Https往API post xml数据
     *
     * @param url API地址
     * @param xmlObj 要提交的XML数据对象
     * @param mchId 商户ID
     * @param certPath 证书位置
     * @return
     */
    public  String postData(String url, String xmlObj, String mchId, String certPath)  throws Exception{
//        certPath = "C:\\Users\\tww\\Desktop\\whs\\apiclient_cert.p12";
//        // 加载证书
//        try {
//            initCert(mchId, certPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        String result = null;
//        HttpPost httpPost = new HttpPost(url);
//        // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
//        StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
//        httpPost.addHeader("Content-Type", "text/xml");
//        httpPost.setEntity(postEntity);
//        // 根据默认超时限制初始化requestConfig
//        requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
//        // 设置请求器的配置
//        httpPost.setConfig(requestConfig);
//        try {
//            HttpResponse response = null;
//            try {
//                response = httpClient.execute(httpPost);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            HttpEntity entity = response.getEntity();
//            try {
//                result = EntityUtils.toString(entity, "UTF-8");
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } finally {
//            httpPost.abort();
//        }
        String key = mchId;
        // 证书的路径
        String path = certPath;
        // 指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 读取本机存放的PKCS12证书文件
//        File file = new File(path);
        File file = ResourceUtils.getFile(path);
//        InputStream in = new FileInputStream(file);
        FileInputStream in = new FileInputStream(file);
        try {
            // 指定PKCS12的密码(商户ID)
            keyStore.load(in, key.toCharArray());
        } finally {
            in.close();
        }
        SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom().loadKeyMaterial(
                keyStore,
                key.toCharArray())
                .build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
        );
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
            HttpPost httpost = new HttpPost(url); // 设置响应头信息
            httpost.setEntity(new StringEntity(xmlObj, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return result;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    public static String doRefund2(String url, String data,String cert_url,String mch_id) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //本地获取
        File file = ResourceUtils.getFile(cert_url);
//        FileInputStream is = new FileInputStream(new File("C:\\Users\\tww\\Desktop\\wohaoshuai\\apiclient_cert.p12"));
        FileInputStream is = new FileInputStream(file);
        //部署jar包获取
//        InputStream is = WordUtil.class.getClassLoader().getResourceAsStream(cert_url);
        try {
            keyStore.load(is, mch_id.toCharArray());
        } finally {
            is.close();
        }
        // Trust own CA and all self-signed certs
        SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom().loadKeyMaterial(
                keyStore,
                mch_id.toCharArray())
                .build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslcontext,
                new String[]{"TLSv1"},
                null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER
        );
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        try {
            HttpPost httpost = new HttpPost(url); // 设置响应头信息
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
                EntityUtils.consume(entity);
                return jsonStr;
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    /**
     * 加载证书
     *
     * @param mchId 商户ID
     * @param certPath 证书位置
     * @throws Exception
     */
    private void initCert(String mchId, String certPath) throws Exception {
        // 证书密码，默认为商户ID
        String key = mchId;
        // 证书的路径
        String path = certPath;
        // 指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 读取本机存放的PKCS12证书文件
        File file = new File(path);
//        InputStream in = new FileInputStream(file);
        FileInputStream in = new FileInputStream(file);
        try {
            // 指定PKCS12的密码(商户ID)
            keyStore.load(in, key.toCharArray());
        } finally {
            in.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
        SSLConnectionSocketFactory sslsf =
                new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null,
                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

}
